import { ElMessage } from 'element-plus'
import axios from 'axios'
import { adminStore } from '../stores/admin'
export const baseURL = 'https://api.tianzhongli.shop/'
const instance = axios.create({
    baseURL,
    timeout: 30000,
})
instance.interceptors.request.use(
    config => {
        const useAdminStore = adminStore()
        const profile = useAdminStore.profile
        if (profile.token) {
            config.headers.Authorization = `${profile.token}`
        }
        return config
    },
    err => {
        return Promise.reject(err)
    }
)
instance.interceptors.response.use(
    res => {
        return res.data.data
    },
    err => {
        // token过期处理，让用户重新登录
        if (
            err.response.data.code == 0 &&
            err.response.data.message == 'The token is expired.'
        ) {
            ElMessage.error('token失效，请重新登录')
            const useAdminStore = adminStore()
            useAdminStore.setAdmin({})
            router.push('/login')
            return
        }
        if (err.response && err.response.status == 401) {
            const useAdminStore = adminStore()
            useAdminStore.setAdmin({})
        }
        return Promise.reject(err)
    }
)
export default (url, method = 'get', submitData) => {
    return instance({
        url,
        method,
        [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData,
    })
}
